import { createSlice, createSelector } from '@reduxjs/toolkit';

// 从 localStorage 获取初始标签页状态，如果不存在则使用默认值
const getInitialTabsState = () => {
  try {
    const savedTabs = localStorage.getItem('tabs');
    const savedActiveKey = localStorage.getItem('activeTabKey');
    
    if (savedTabs && savedActiveKey) {
      const tabs = JSON.parse(savedTabs);
      const activeKey = savedActiveKey;
      
      // 确保首页标签页始终存在
      const homeTabExists = tabs.find(tab => tab.key === '/home');
      if (!homeTabExists) {
        tabs.unshift({
          key: '/home',
          label: '首页',
          closable: false,
          icon:'HomeFilled',
          name:'home'
        });
      }
      
      return {
        tabs,
        activeKey
      };
    }
  } catch (e) {
    console.error('Failed to parse tabs from localStorage:', e);
  }
  
  // 默认状态
  return {
    tabs: [
      {
        key: '/home',
        label: '首页',
        closable: false,
        icon:'HomeFilled',
        name: 'home',
      }
    ],
    activeKey: '/home'
  };
};

// 初始状态
const initialState = getInitialTabsState();

// 创建 tabs slice
const tabsSlice = createSlice({
  name: 'tabs',
  initialState,
  reducers: {
    // 添加标签页
    addTab: (state, action) => {
      const newTab = action.payload;
      // 检查标签页是否已存在
      const existingTab = state.tabs.find(tab => tab.key === newTab.key);
      
      if (!existingTab) {
        state.tabs.push(newTab);
      }
      
      // 设置为当前激活的标签页
      state.activeKey = newTab.key;
      
      // 保存到 localStorage
      saveTabsToLocalStorage(state);
    },
    
    // 关闭标签页
    removeTab: (state, action) => {
      const keyToRemove = action.payload;
      // 检查标签页是否可关闭
      const tabToRemove = state.tabs.find(tab => tab.key === keyToRemove);
      let removedTabIndex = -1;
      
      if (tabToRemove && tabToRemove.closable !== false) {
        removedTabIndex = state.tabs.findIndex(tab => tab.key === keyToRemove);
        state.tabs = state.tabs.filter(tab => tab.key !== keyToRemove);
      }
      
      // 如果关闭的是当前激活的标签页，需要设置新的激活标签页
      if (state.activeKey === keyToRemove) {
        // 选择下一个激活标签页的逻辑：
        // 1. 如果有相邻的右侧标签页，选择它
        // 2. 如果没有右侧标签页，选择左侧标签页
        // 3. 如果没有其他标签页，保持空字符串
        if (state.tabs.length > 0) {
          if (removedTabIndex >= 0 && removedTabIndex < state.tabs.length) {
            // 选择原来位置的标签页
            state.activeKey = state.tabs[removedTabIndex].key;
          } else if (removedTabIndex >= state.tabs.length) {
            // 如果删除的是最后一个标签页，选择新的最后一个
            state.activeKey = state.tabs[state.tabs.length - 1].key;
          } else {
            // 默认选择第一个标签页
            state.activeKey = state.tabs[0].key;
          }
        } else {
          state.activeKey = '';
        }
      }
      
      // 保存到 localStorage
      saveTabsToLocalStorage(state);
    },
    
    // 设置当前激活的标签页
    setActiveTab: (state, action) => {
      state.activeKey = action.payload;
      // 保存到 localStorage
      saveTabsToLocalStorage(state);
    },
    
    // 关闭其他标签页
    closeOtherTabs: (state, action) => {
      const keyToKeep = action.payload;
      state.tabs = state.tabs.filter(tab => 
        tab.key === keyToKeep || tab.closable === false
      );
      state.activeKey = keyToKeep;
      
      // 保存到 localStorage
      saveTabsToLocalStorage(state);
    },
    
    // 关闭所有标签页
    closeAllTabs: (state) => {
      // 保留不可关闭的标签页
      state.tabs = state.tabs.filter(tab => tab.closable === false);
      // 如果当前激活的标签页被关闭了，激活第一个标签页
      if (state.tabs.length > 0 && !state.tabs.find(tab => tab.key === state.activeKey)) {
        state.activeKey = state.tabs[0].key;
      } else if (state.tabs.length === 0) {
        state.activeKey = '';
      }
      
      // 保存到 localStorage
      saveTabsToLocalStorage(state);
    },
    
    // 重置标签页状态（用于用户登出时）
    resetTabs: (state) => {
      // 重置为默认状态
      state.tabs = [
        {
          key: '/home',
          label: '首页',
          closable: false,
          icon:'HomeFilled',
          name:'home'
        }
      ];
      state.activeKey = '/home';
      
      // 清除 localStorage 中的标签页数据
      try {
        localStorage.removeItem('tabs');
        localStorage.removeItem('activeTabKey');
      } catch (e) {
        console.error('Failed to remove tabs from localStorage:', e);
      }
    }
  }
});

// 保存标签页状态到 localStorage
const saveTabsToLocalStorage = (state) => {
  try {
    localStorage.setItem('tabs', JSON.stringify(state.tabs));
    localStorage.setItem('activeTabKey', state.activeKey);
  } catch (e) {
    console.error('Failed to save tabs to localStorage:', e);
  }
};

// 根据 activeKey 获取对应的 tab
export const selectActiveTab = (state) => {
  return state.tabs.tabs.find(tab => tab.key === state.tabs.activeKey) || null;
};

// 创建记忆化的 selector 用于获取带图标的标签页数据
export const selectTabsWithIcons = createSelector(
  [state => state.tabs.tabs],
  (tabs) => tabs.map(tab => ({
    ...tab,
    icon: tab.icon ? tab.icon : null
  }))
);

// 导出 actions
export const { addTab, removeTab, setActiveTab, closeOtherTabs, closeAllTabs, resetTabs } = tabsSlice.actions;

// 导出 reducer
export default tabsSlice.reducer;